import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Pagination, Spin, Timeline, Card } from 'antd';
import { getAllBlogs } from '@/api/blog';
import TimeCard from '@/components/timeCard';
import css from './index.module.less';

export default function Index() {
	const item = sessionStorage.getItem('info')
	const info = JSON.parse(item);
	const [blogs, setBlogs] = useState([]);
	const [current, setCurrent] = useState(1);
	const [size, setSize] = useState(5);
	const [total, setTotal] = useState(5);
	const [spinning, setSpinning] = useState(true);
	useEffect(() => {
		const id = info.id;
		getAllBlogs(current, size, id).then((res) => {
			setSpinning(true);
			if (res.code === 200) {
				setBlogs(res.data.blogDtos);
				setTotal(res.data.total);
				setSpinning(false);
			}
		})
	}, []);
	const onChange = (current, size) => {
		const id = info.id;
		getAllBlogs(current, size, id).then((res) => {
			setSpinning(true);
			if (res.code === 200) {
				setBlogs(res.data.blogDtos);
				setTotal(res.data.total);
				setSpinning(false);
			}
		})
		setCurrent(current);
	}
	const onShowSizeChange = (current, size) => {
		const id = info.id;
		getAllBlogs(current, size, id).then((res) => {
			setSpinning(true);
			if (res.code === 200) {
				setBlogs(res.data.blogDtos);
				setTotal(res.data.total);
				setSpinning(false);
			}
		})
		setSize(size);
	}
	const navigate = useNavigate();
	const toDetail = (data) => {
		navigate(`/blogDetail/${data.blog.id}`);
	}
	const colors = ["magenta", "red", "orange", "green", "yellow", "blue", "gold"];
	return (
		<div className={css.content}>
			<Spin tip='Loading...' spinning={spinning} className={css.spinning} />
			<Card>
				<Timeline>
					{blogs.length === 0? <></> :
						blogs.map((blog, index) => {
							return (
								<Timeline.Item color={colors[Math.round(Math.random() * colors.length)]} key={index} onClick={() => toDetail(blog)} style={{cursor: 'pointer', paddingBottom: '10px'}}><TimeCard data={blog} /></Timeline.Item>
							);
						})
					}
				</Timeline>
				<Pagination
					current={current} onChange={onChange}
					onShowSizeChange={onShowSizeChange}
					defaultPageSize={5}
					pageSizeOptions={[5, 10, 15]}
					total={total}
				/>
			</Card>
		</div>

	)
}
